<template>
    <a-drawer title="刺点地图" 
    placement="left" 
    width="100%" 
    :closable="true" 
    :visible="cd_map_drawer_visible"
    :maskClosable="false"
    :bodyStyle="{ padding: '0px' }"
    :maskStyle="{ display: 'none' }"
    :mask="false"
    @close="cd_map_drawer_close" 
    class="my-drawer">
        <div class="layout-root">
            <div class="layout-content no-header map-container-src">
                <div class="layout-left" id="left-item" style="width: 80%; overflow: auto;">
                    <div class="layout-right-content" style="padding:0px;">
                        <div id="map-container-src" class="map-container-src">
                            <a-row style="height:calc(100% - 80px)">
                                <a-col :span="12" style="height: 100%;">
                                    <div id="point-mapcontainer-left" class="map-container"
                                        style="height: 100%;width: 100%;position: relative;" @mousemove="mousemove('left')">
                                        <div :class="['message-maps']" @click="tipsclick('left')">
                                            <div style="width: 90%;background-color: #bec0c1;color: white;margin: 0 auto;">
                                                <a-row>
                                                    <div style="text-align: center;width: 100%;">影像名:{{
                                                        left_standard_img?.name }} </div>
                                                </a-row>
                                                <a-row>
                                                    <div style="text-align: center;width: 100%;">点位置: {{
                                                        get_standard_img_position('left')}}</div>
                                                </a-row>
                                            </div>
                                        </div>
                                    </div>
                                </a-col>
                                <a-col :span="12" style="height: 100%;">
                                    <div id="point-mapcontainer-right" class="map-container"
                                        style="height: 100%;width: 100%;position: relative;"
                                        @mousemove="mousemove('right')">
                                        <div :class="['message-maps']">
                                            <div style="width: 90%;background-color: #bec0c1;color: white;margin: 0 auto;">
                                                <a-row>
                                                    <div style="text-align: center;width: 100%;">影像名:{{
                                                        right_standard_img?.name }} </div>
                                                </a-row>
                                                <a-row>
                                                    <div style="text-align: center;width: 100%;">点位置: {{
                                                        get_standard_img_position('right') }}</div>
                                                </a-row>
                                            </div>
                                        </div>
                                    </div>
                                </a-col>
                            </a-row>
                        </div>
                    </div>
                </div>
                <div class="layout-right" id="layoutright"
                    style="width: 460px; overflow: auto;box-sizing: border-box;position: relative;">
                    <div class="search_result show">
                        <div class="result_btn" style="margin-top: 10px;margin-left: 10px;">
                            <a-row style="margin-bottom: 5px;">
                                <a-col :span="16">
                                    <a-space>
                                        <a-tooltip placement="bottom" color="rgb(19 32 41 / 75%)">
                                            <template #title>清空全部点</template>
                                            <setting-outlined style="font-size: 22px;vertical-align: middle;color: #3bb9d1;"
                                                @click="clear_nd_point_details" />
                                        </a-tooltip>
                                    </a-space>
                                    
                                </a-col>
                                <a-col :span="8">
                                    <a-space>
                                        <a-tooltip placement="bottom" color="rgb(19 32 41 / 75%)">
                                            <template #title>设置(一些常规设置)</template>
                                            <setting-outlined style="font-size: 22px;vertical-align: middle;color: #3bb9d1;"
                                                @click="setting_jianju" />
                                        </a-tooltip>
                                        <a-tooltip placement="bottom" color="rgb(19 32 41 / 75%)">
                                            <template #title>完成刺点</template>
                                            <check-circle-outlined
                                                style="font-size: 22px;vertical-align: middle;color: #3bb9d1;"
                                                @click="end_point_cd" />
                                        </a-tooltip>
                                    </a-space>
                                </a-col>
                            </a-row>
                        </div>
                        <div class="result_box">
                            <a-table 
                            :data-source="nd_point_details" 
                            :columns="nd_point_details_table_columns"
                            class="records_table" size="small" :showHeader="true" tableLayout="fixed"
                            :pagination="false" bordered rowKey="name">
                                <template #bodyCell="{ text, record, index, column }">
                                    <!-- <template v-if="column.dataIndex == 'status'">
                                        <a-badge :status="get_nd_point_detail_status(record)" />
                                    </template> -->
                                    <template v-if="column.dataIndex == 'type'">
                                        <span v-if="record.type == 'ys'">原始</span>
                                        <span v-if="record.type == 'sim'">仿真</span>
                                    </template>
                                    <template v-if="column.dataIndex == 'operation'">
                                        <a href="javascript:;" @click="set_point_to_map(record)" 
                                        :style="left_standard_img?.point_name==record?.name?'font-weight: 1000;color: #c75239;':''">显示</a>
                                        <a-divider type="vertical" />
                                        <a-divider type="vertical" />
                                        <a-divider type="vertical" />
                                        <a-divider type="vertical" />
                                        <a-popconfirm title="确定删除此点吗?" ok-text="确定"
                                            cancel-text="取消" @confirm="delete_point(record, index)">
                                            <a href="javascript:;">删</a>
                                        </a-popconfirm>
                                    </template>
                                </template>
                            </a-table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </a-drawer>
    <a-modal class="my-modal short" v-model:visible="setting_modal_show" title="移动间距" @ok="setting_modal_ok" width="40%"
        :maskClosable="false" :centered="true" :destroyOnClose="true">
        <div class="body-content">
            <a-row>
                <a-col :span="8">移动间距</a-col>
                <a-col :span="11">
                    <a-input-number v-model:value="step_sacle" size="small" :min="0.1" :max="20" :step="0.1" />
                </a-col>
                <a-col :span="5">
                    <a-tooltip placement="bottom" color="rgb(19 32 41 / 75%)">
                        <template #title>上下左右键调节的间距.间距为屏幕像素的*移动间距</template>
                        <question-outlined style="font-size: 22px;vertical-align: middle;color: #3bb9d1;" />
                    </a-tooltip>
                </a-col>
            </a-row>
        </div>
    </a-modal>
</template>
<script>
// 仅仅针对左右tif一致 点不同的CCD CTR
export default {
    data() {
        return {
            cd_map_drawer_visible: false,
            xml_object:{},
            match_points_result:[],



            nd_point:{}, //刺点的点
            nd_point_details:[],//刺点的片子数组
            nd_point_details_table_columns: [
                {
                    title: '名称',
                    dataIndex: 'name',
                    align: 'center',
                    width: 60,
                    ellipsis: true,
                },
                {
                    title: '类型',
                    dataIndex: 'type',
                    align: 'center',
                    width: 40,
                    ellipsis: true,
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    align: 'center',
                    width: 20,
                },
                {
                    title: '操作',
                    width: 60,
                    dataIndex: 'operation',
                    align: 'center'
                },
            ],
            left_map: undefined, //左边地图
            left_view: undefined, //左边地图view
            left_standard_img: undefined, //左边地图底图 point_detail

            right_map: undefined, //右边地图
            right_view: undefined, //右边地图view
            right_point_source: undefined, //右边地图图层
            right_standard_img: undefined, //右边地图底图 point_detail

            uclick:"", //鼠标在左右哪个地图的指示器
            res: 0,
            step: 0,
            //设置
            setting_modal_show:false,
            step_sacle: 2,
            //mitt
            mitt_cidian_map_id:"",
            mitt_cidian_map_back_id:"",
            
        };
    },
    beforeUnmount() {
        this.$mitt.off('cidian_map',this.mitt_cidian_map_id);
    },
    mounted() {
        setTimeout(() => {
            this.init_keydown();
        }, 300)
        this.mitt_cidian_map_id=this.$mitt.on('cidian_map', async(uid,xml_object)  => {
            this.mitt_cidian_map_back_id=uid
            this.cd_map_drawer_visible=true
            this.xml_object=xml_object
            setTimeout(()=>{
                this.delete_type_img("left")
                this.delete_type_img("right")
                this.get_match_points();
            },500)
        },this?.$?.uid);
    },
    methods: {
        //重置地图
        delete_type_img(type){
            if (type == "left") {
                this.left_map?.setTarget(null);
                this.left_map?.dispose();
                this.left_view=undefined
                this.left_standard_img=undefined
            }
            else if (type == "right") {
                this.right_map?.setTarget(null);
                this.right_map?.dispose();
                this.right_view=undefined
                this.right_standard_img = undefined
            }
        },
        //查询任务病初始化tree
        async get_match_points() {
            this.nd_point_details=[]
            this.$Loading.start();
            this.match_points_result=[]
            this.match_points_result=await this.$apis.get_match_point(this.xml_object)
            this.point_show_type=this.match_points_result?.type
            this.left_standard_img={
                tif:this.match_points_result?.tif,
                name:this.match_points_result?.tif_name,
                in_wkid:3857,
                out_wkid:3857,
                type:"ys",
                point_name:"null",
            }
            this.right_standard_img={
                tif:this.match_points_result?.sim,
                name:this.match_points_result?.sim_name,
                in_wkid:3857,
                out_wkid:3857,
                type:"sim",
            }
            let points=[]
            for (let i = 0; i < this.match_points_result?.points.length; i++) {
                let one_point_old = this.match_points_result?.points[i];
                let one_point ={
                    name:one_point_old?.name,
                    left:{},
                    right:{},
                };
                let ctr_points=one_point_old?.points;
                if(ctr_points?.length==2){
                    let first_point=ctr_points[0];
                    {
                        one_point.left.x=first_point?.x-0;
                        one_point.left.y=-(first_point?.y-0);
                        one_point.left.name=one_point_old?.name;
                    }
                    let second_point=ctr_points[1];
                    {
                        one_point.right.x=second_point?.x-0;
                        one_point.right.y=-(second_point?.y-0);
                        one_point.right.name=one_point_old?.name;
                    }
                }
                points.push(one_point)
            }
            this.nd_point_details=points
            this.$Loading.done();
            this.init_map("left")
            this.init_map("right")
            // this.add_point_to_map()
            return
        },
        clear_nd_point_details(){
            this.nd_point_details=[]
            this.update_point_to_map(undefined,"left")
            this.update_point_to_map(undefined,"right")
        },
        delete_point(record, index) {
            if(record?.name==this.left_standard_img.point_name){
                this.update_point_to_map(undefined,"left")
                this.update_point_to_map(undefined,"right")
                this.left_standard_img.point_name="null"
            }
            this.nd_point_details.splice(index,1)
        },
        set_point_to_map(record){
            let _side="left"
            {
                let center=[record[_side]?.x, record[_side]?.y]
                this.left_view.setCenter(center)
                this.update_point_to_map(center,_side)
            }
            _side="right"
            {
                let center=[record[_side]?.x, record[_side]?.y]
                this.right_view.setCenter(center)
                this.update_point_to_map(center,_side)
            }
            this.left_standard_img.point_name=record?.name
        },
        update_point_to_map(center,_side){
            let _map=_side=="left"?this.left_map:this.right_map
            let _new_point_layer=undefined
            _map.getLayers().forEach((val) => {
                if (val.get('layertype') == 'cd') {
                    _new_point_layer= val
                }
            })
            if(_new_point_layer){
                _new_point_layer.getSource().clear();
                if(center){
                    let feature = new ol.Feature({
                        geometry: new ol.geom.Point(center),
                        properties: {
                            title: "updated"
                        },
                        style: this.point_style("#11f41dd9")
                    });
                    _new_point_layer.getSource().addFeature(feature)
                }
            }
        },
        cd_map_drawer_close(){
            this.cd_map_drawer_visible=false
            //cidian_map_back
        },
        //右边表格点的刺点状态
        get_nd_point_detail_status(record) {
            if(record?.status==3){
                return "success"
            }
            else{
                return "processing"
            }
        },
        //初始化键盘的上下左右方向键
        init_keydown() {
            let that = this;
            document.onkeydown = (e) => {
                let e1 = e || event || window.event || arguments.callee.caller.arguments[0]//事件对象兼容
                let set_key = true
                if (e1) {
                    let keyCode = e1.keyCode
                    if (e1.ctrlKey == true && keyCode == 70) { } //Ctrl+F
                    if (that.uclick) {
                        if (keyCode == 37) {//左箭头
                            this.left_move()
                        } else if (keyCode == 39) {//右箭头
                            this.right_move()
                        } else if (keyCode == 38) {//上箭头
                            this.up_move()
                        } else if (keyCode == 40) {//下箭头
                            this.down_move()
                        }
                        else {
                            set_key = false
                        }
                    }
                    else {
                        set_key = false
                    }
                }
                if (set_key) {
                    e.stopPropagation();
                    e.preventDefault();
                }
            }
        },
        //上面显示的点的坐标 根据img_type == "ddom"/"ys"进行显示
        get_standard_img_position(type) {
            let lon_val=0.0;
            let lat_val=0.0;
            let standard_img_index=this.get_img_index(this.left_standard_img)
            if(standard_img_index>=0){
                lon_val=this.nd_point_details[standard_img_index][type].x
                lat_val=this.nd_point_details[standard_img_index][type].y
            }
            let position = `${lon_val?.toFixed(6)}--${lat_val?.toFixed(6)}`
            return position
        },
        init_map(_side="left") {
            let one_img=_side=="left"?this.left_standard_img:this.right_standard_img
            let _map=_side=="left"?this.left_map:this.right_map
            let target=_side=="left"?"point-mapcontainer-left":"point-mapcontainer-right"
            let projection = `EPSG:${one_img?.out_wkid}`
            let center=[0, 0]
            let _view= new ol.View({
                projection: projection,
                zoom: 15,
                center: center,
                enableRotation: false,
            });
            _map = new ol.Map({
                controls: [],
                maxTilesLoading: 18,
                view: _view,
                layers: [],
                target: target,
            });
            _map.removeInteraction(_map.getInteractions().getArray().find(interaction => {
                return interaction instanceof ol.interaction.DoubleClickZoom;
            }));
            _map.removeInteraction(_map.getInteractions().getArray().find(interaction => {
                return interaction instanceof ol.interaction.DblClickDragZoom;
            }));
            _map.set("old_zoom", 0)
            //建立一个新的用于刺点
            {
                let new_point_source = new ol.source.Vector({
                    features: []
                });
                let new_point_layer = new ol.layer.Vector({
                    source: new_point_source,
                    style: this.point_style("#11f41dd9")
                });
                new_point_layer.set("layertype","cd")
                new_point_layer.setZIndex(10);
                _map.addLayer(new_point_layer);
            }
            {
                let url = `${this.$store.state.true_address}/ser/tile?layer=${one_img?.tif}&tilematrix={z}&tilerow={y}&tilecol={x}&in_wkid=${one_img?.in_wkid}&out_wkid=${one_img?.out_wkid}`
                let xyz = new ol.source.XYZ({
                    projection: projection,
                    tileUrlFunction: function ([z, Col, Row], b) {
                        return this.urlx.replace("{z}", z).replace("{x}", Col).replace("{y}", Row)
                    },
                })
                xyz.projectionx = projection;
                xyz.urlx = url;
                let tile_layer = new ol.layer.Tile({
                    source: xyz,
                    maxZoom: 16,
                })
                tile_layer.set("layertype", "tile")
                tile_layer.setZIndex(0);
                _map.addLayer(tile_layer);
                let ImageLayer = new ol.layer.Image({
                    minZoom: 16,
                    source: this.getImageStatic(),
                    interpolate: false,
                })
                ImageLayer.set("layertype", "static")
                ImageLayer.set("layerfile", one_img?.tif)
                ImageLayer.set("in_wkid", one_img?.in_wkid)
                ImageLayer.set("out_wkid", one_img?.out_wkid)
                ImageLayer.setZIndex(1);
                _map.addLayer(ImageLayer);
            }
            let that = this;
            _map.on("moveend", async ({ frameState, map, target, type }) => {
                let zoom = map.getView().getZoom();
                let res = map.getView().getResolution();
                let old_zoom = map.get('old_zoom')
                let extent = map.getView().calculateExtent();
                let layers = map.getLayers().getArray();
                let _tile_layers = layers.filter((val) => {
                    return val.get('layertype') == 'tile'
                })
                let _static_layers = layers.filter((val) => {
                    return val.get('layertype') == 'static'
                })
                if (zoom >= 16) {
                    this.show_hide_layer(_tile_layers, false)
                    this.show_hide_layer(_static_layers, true)
                    for (let i = 0; i < _static_layers.length; i++) {
                        let _static_layer = _static_layers[i]
                        let tif_file = _static_layer.get('layerfile')
                        let tif_in_wkid = _static_layer.get('in_wkid')
                        let tif_out_wkid = _static_layer.get('out_wkid')
                        if (zoom < 20) {
                            let png_result = await that.$apis.get_static_img(`${this.$store.state.true_address}/ser/statictile?layer=${tif_file}&extent=${JSON.stringify(extent)}&in_wkid=${tif_in_wkid}&out_wkid=${tif_out_wkid}`)
                            png_result = png_result?.result
                            if (png_result?.img) {
                                let newSource = that.getImageStatic(png_result.extent, png_result.img)
                                _static_layer.setSource(newSource)
                                newSource.refresh()
                            }
                        }
                    }
                }
                else {
                    this.show_hide_layer(_tile_layers, true)
                    this.show_hide_layer(_static_layers, false)
                }
                this.res = res
                this.step = this.res * this.step_sacle;
                map.set("old_zoom", zoom - 0)
            })
            _map.on('dblclick', (event) => {
                that.map_dblclick(event?.coordinate,_side)
            });
            _map.updateSize();
            _map.set("old_zoom",0);
            _map.set("show_side", _side);
            if (_side == "left") {
                this.left_map= _map
                this.left_view = _view
            }
            else if (_side == "right") {
                this.right_map = _map
                this.right_view = _view
            }
        },
        //点的Style
        point_style(color = "#d6144") {
            return new ol.style.Style({
                image: new ol.style.Icon({
                    src: `data:image/svg+xml;base64,` + window.btoa(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" focusable="false" class="" data-icon="plus" width="20px" height="20px" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896" style="color: ${color};"><defs><style></style></defs><path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path><path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path></svg>`),
                    size: [20, 20],
                })
            })
        },
        getImageStatic(imageExtent = [], url = "") {
            return new ol.source.ImageStatic({
                imageExtent: imageExtent,
                interpolate: false,
                url: url,
            })
        },
        show_hide_layer(_tile_layers, visible) {
            for (let i = 0; i < _tile_layers.length; i++) {
                _tile_layers[i].setVisible(visible)
            }
        },
        get_img_index(standard_img){
            let find_index=this.nd_point_details?.findIndex((val)=>{
                return val?.name==standard_img?.point_name
            })
            return find_index
        },
        //鼠标双击
        map_dblclick(coordinate,_side) {
            let new_lon_val= coordinate[0]
            let new_lat_val = coordinate[1]
            let _map = this.uclick == 'left'?this.left_map:this.right_map
            let standard_img_index=this.get_img_index(this.left_standard_img)
            if(standard_img_index>=0){
                this.nd_point_details[standard_img_index][_side].x= new_lon_val
                this.nd_point_details[standard_img_index][_side].y=new_lat_val
                this.update_geometry(_map, new_lon_val, new_lat_val)
            }
            else{
                let new_point_name=(new Date()).getTime();
                this.nd_point_details.push({
                    name:new_point_name,
                    left:{
                        x:new_lon_val,
                        y:new_lat_val,
                    },
                    right:{
                        x:new_lon_val,
                        y:new_lat_val,
                    },
                })
                this.left_standard_img.point_name=new_point_name
                this.update_geometry(this.left_map, new_lon_val, new_lat_val)
                this.update_geometry(this.right_map, new_lon_val, new_lat_val)
            }
        },
        //鼠标在div上的移动确定是左还是右
        mousemove(type){
            if(this.uclick!=type){
                this.uclick=type
            }
        },
        left_move() {
            let _map = this.uclick == 'left'?this.left_map:this.right_map
            let standard_img_index=this.get_img_index(this.left_standard_img)
            if(standard_img_index>=0){
                let old_lon=this.nd_point_details[standard_img_index][this.uclick].x
                let old_lat=this.nd_point_details[standard_img_index][this.uclick].y
                let new_lon_val = old_lon - this.step;
                let new_lat_val = old_lat;
                this.nd_point_details[standard_img_index][this.uclick].x= new_lon_val
                this.nd_point_details[standard_img_index][this.uclick].y=new_lat_val
                this.update_geometry(_map, new_lon_val, new_lat_val)
            }
        },
        right_move() {
            let _map = this.uclick == 'left'?this.left_map:this.right_map
            let standard_img_index=this.get_img_index(this.left_standard_img)
            if(standard_img_index>=0){
                let old_lon=this.nd_point_details[standard_img_index][this.uclick].x
                let old_lat=this.nd_point_details[standard_img_index][this.uclick].y
                let new_lon_val = old_lon + this.step;
                let new_lat_val = old_lat;
                this.nd_point_details[standard_img_index][this.uclick].x= new_lon_val
                this.nd_point_details[standard_img_index][this.uclick].y=new_lat_val
                this.update_geometry(_map, new_lon_val, new_lat_val)
            }
        },
        up_move() {
            let _map = this.uclick == 'left'?this.left_map:this.right_map
            let standard_img_index=this.get_img_index(this.left_standard_img)
            if(standard_img_index>=0){
                let old_lon=this.nd_point_details[standard_img_index][this.uclick].x
                let old_lat=this.nd_point_details[standard_img_index][this.uclick].y
                let new_lon_val = old_lon ;
                let new_lat_val = old_lat+ this.step;
                this.nd_point_details[standard_img_index][this.uclick].x= new_lon_val
                this.nd_point_details[standard_img_index][this.uclick].y=new_lat_val
                this.update_geometry(_map, new_lon_val, new_lat_val)
            }
        },
        down_move() {
            let _map = this.uclick == 'left'?this.left_map:this.right_map
            let standard_img_index=this.get_img_index(this.left_standard_img)
            if(standard_img_index>=0){
                let old_lon=this.nd_point_details[standard_img_index][this.uclick].x
                let old_lat=this.nd_point_details[standard_img_index][this.uclick].y
                let new_lon_val = old_lon ;
                let new_lat_val = old_lat- this.step;
                this.nd_point_details[standard_img_index][this.uclick].x= new_lon_val
                this.nd_point_details[standard_img_index][this.uclick].y=new_lat_val
                this.update_geometry(_map, new_lon_val, new_lat_val)
            }
        },
        //更新坐标到地图
        update_geometry(_map,new_lon_val, new_lat_val) {
            let _new_point_layer=undefined
            _map.getLayers().forEach((val) => {
                if (val.get('layertype') == 'cd') {
                    _new_point_layer= val
                }
            })
            if(_new_point_layer){
                _new_point_layer.getSource().clear();
                let new_point=[new_lon_val, new_lat_val]
                let feature = new ol.Feature({
                    geometry: new ol.geom.Point(new_point),
                    properties: {
                        title: "updated"
                    },
                    style: this.point_style("#11f41dd9")
                });
                _new_point_layer.getSource().addFeature(feature)
            }
        },
        async end_point_cd(){
            console.log(this.nd_point_details)
            if(this.nd_point_details?.length>1){
                this.$message.info("点的数量只能为1个...")
                return
            }
            let points=[]
            for (let i = 0; i < this.nd_point_details?.length; i++) {
                let one_nd_point_detail = this.nd_point_details[i];
                let one_point={
                    name:one_nd_point_detail?.name,
                    points:[]
                }
                if(one_nd_point_detail?.left){
                    one_point.points.push({
                        x: one_nd_point_detail?.left?.x-0,
                        y: -(one_nd_point_detail?.left?.y-0)
                    })
                }
                if(one_nd_point_detail?.right){
                    one_point.points.push({
                        x: one_nd_point_detail?.right?.x-0,
                        y: -(one_nd_point_detail?.right?.y-0)
                    })
                }
                points.push(one_point)
            }
            this.$mitt.oemit('cidian_map_back',{
                xml_object:this.xml_object,
                points:points
            },this.mitt_cidian_map_back_id);
            this.delete_type_img("left")
            this.delete_type_img("right")
            this.cd_map_drawer_close()
        },
        //设置移动间距
        setting_jianju(){
            this.setting_modal_show=true
        },
        //设置
        setting_modal_ok(){
            this.setting_modal_show=false
        },
    },
};
</script>


